package com.whd.exection;

import com.whd.domain.ResultVo;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author whd
 * @date 2023/7/7 18:54:13
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ArithmeticException.class)
    public ResultVo numException(ArithmeticException e){
        e.printStackTrace();
        return ResultVo.fail("出错了");
    }

    @ExceptionHandler(NullPointerException.class)
    public ResultVo nullPaintException(NullPointerException e) {
        e.printStackTrace();
        return ResultVo.fail("出错了");
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVo methodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<FieldError> errors = e.getFieldErrors();
        Map<String, String> map = new HashMap<>();
        for (FieldError error : errors) {
            map.put(error.getField(), error.getDefaultMessage());
        }
        return ResultVo.fail(map);
    }
    @ExceptionHandler(Exception.class)
    public ResultVo Exception(Exception e) {
        e.printStackTrace();
        return ResultVo.fail(e.toString());
    }

}
